#include<bits/stdc++.h>
#include<windows.h>
using namespace std;
const int blockSize = 100; // 每个逻辑块的大小
int main(){
    ofstream diskFile("hd.txt");
    for(int i=1;i<=10;i++){
        string block="Block("+to_string(i)+"): message...";
        block.resize(blockSize,'\0');
        diskFile<<block;
    }
    diskFile.close();

    //创建命名管道
    HANDLE hPipe=CreateNamedPipe(
        TEXT("\\\\.\\Pipe\\pipe"),
        PIPE_ACCESS_DUPLEX,
        PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
        1,
        1024,
        1024,
        0,
        NULL
    );
    if(hPipe==INVALID_HANDLE_VALUE){
        cerr<<"Create pipe failed: "<<GetLastError()<<endl;
        system("pause");
        return 0;
    }

    struct timeval tv;
    //等待客户端连接管道
    if(ConnectNamedPipe(hPipe,NULL)){

        //开始读取数据
        CHAR Buffer[101];
        CHAR contents[101];
        memset(Buffer,'\0',sizeof(Buffer));
        memset(contents,'\0',sizeof(contents));
        DWORD dwNumberOfBytesRead=0;
        DWORD dwNumberOfBytesWritten=0;

        for(int i=0;i<10;i++){
            //接收到worker的发送的逻辑块号
            ReadFile(hPipe,Buffer,sizeof(Buffer),&dwNumberOfBytesRead,NULL);
            int blockNum=stoi(Buffer);
            memset(Buffer,'\0',sizeof(Buffer));
            
            //将块中的数据返回给worker
            ifstream diskFile("hd.txt");
            diskFile.seekg( (blockNum-1) * 100, ios::beg);
            memset(contents,'\0',sizeof(contents));
            diskFile.read(contents, 100);
            diskFile.close();
            WriteFile(hPipe,contents,strlen(contents),&dwNumberOfBytesWritten,NULL);
        }
        
    }
    FlushFileBuffers(hPipe);
    DisconnectNamedPipe(hPipe);
	CloseHandle(hPipe);//关闭管道
	system("pause");
    return 0;
}